package com.hig.onlineexam.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hig.exam.domain.ExamTaskManager;
import com.hig.exam.service.IExamTaskManagerService;
import com.hig.onlineexam.domain.ExamFinishAnswer;
import com.hig.onlineexam.domain.dto.ExamQuestionsData;
import com.hig.onlineexam.mapper.ExamFinishAnswerMapper;
import com.hig.questions.domain.ExamQuestionsAnswer;
import com.hig.questions.domain.ExamQuestionsProperty;
import com.hig.questions.mapper.ExamQuestionsPropertyMapper;
import com.hig.questions.service.IExamQuestionsAnswerService;
import com.hig.utils.DigitUtils;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hig.onlineexam.domain.dto.ExamQuestionsContentData;
import com.hig.onlineexam.mapper.ExamQuestionsContentDataMapper;
import com.hig.onlineexam.service.IExamQuestionsContentDataService;

@Service
public class ExamQuestionsContentDataServiceImpl implements IExamQuestionsContentDataService {
	@Autowired
	ExamQuestionsContentDataMapper examQuestionsContentDataMapper;
	
	
	@Override
	public ExamQuestionsContentData selectExamQuestionsContent(ExamQuestionsContentData questionsContentData) {
		// TODO Auto-generated method stub
		return examQuestionsContentDataMapper.selectExamQuestionsContent(questionsContentData);
	}
	@Autowired
	private ExamQuestionsPropertyMapper propertyMapper;

	@Autowired
	private ExamFinishAnswerMapper finishAnswerMapper;


	@Autowired
	private RedisCache redisCache;

	@Autowired
	private IExamTaskManagerService examTaskManagerService;

	@Autowired
	private TokenService tokenService;
	@Autowired
	private IExamQuestionsContentDataService examQuestionsContentDataService;

	@Autowired
	private IExamQuestionsAnswerService examQuestionsAnswerService;
	@Override
	public ExamQuestionsData convertQuestion(ExamQuestionsContentData examQuestionsContentData) {
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		Long userId = loginUser.getUser().getUserId();
		String examCode = examQuestionsContentData.getExamCode();
		ExamTaskManager examTaskManager = examTaskManagerService.selectExamTaskManagerById(examCode);

		if (ObjectUtil.isNull(examTaskManager)) {
			throw new RuntimeException("查询不到考试信息");
		}

		String buildType = examTaskManager.getBuildType();
		ExamQuestionsContentData contentData = examQuestionsContentDataService.selectExamQuestionsContent(examQuestionsContentData);

		// 转换题号
		String questionsCode = contentData.getQuestionsCode();
		String str = DigitUtils.toChinese(String.valueOf(contentData.getQuestionsNumber()));
		contentData.setQuestionsNumberText("第" + str + "题");

		List<ExamQuestionsAnswer> examQuestionsOptionList = examQuestionsAnswerService.selectExamQuestionsOptionList(examQuestionsContentData.getQuestionsCode());

		// 如果是随机组卷（buildType == "3"），检查 Redis 是否已经保存了随机顺序
		// 尝试从 Redis 获取已缓存的选项顺序映射
		Map<String, Object> cachedMap = redisCache.getCacheMap(examCode + questionsCode + userId);
		if ("3".equals(buildType)) {


			if (cachedMap == null || cachedMap.isEmpty()) {
				// 如果 Redis 中没有数据，则打乱选项
				List<String> optionCodes = new ArrayList<>();
				for (ExamQuestionsAnswer answer : examQuestionsOptionList) {
					optionCodes.add(answer.getOptionCode());
				}
				Collections.shuffle(optionCodes);

				HashMap<String, Object> map = new HashMap<>();
				for (int i = 0; i < examQuestionsOptionList.size(); i++) {
					ExamQuestionsAnswer examQuestionsAnswer = examQuestionsOptionList.get(i);
					String ordinaryQCode = examQuestionsAnswer.getOptionCode();
					String nowQCode = optionCodes.get(i);
					examQuestionsAnswer.setOptionCode(nowQCode);
					map.put(ordinaryQCode, nowQCode);
				}

				// 将随机顺序映射存入 Redis
				redisCache.setCacheMap(examCode + questionsCode + userId, map);
			} else {
				// 如果 Redis 中有数据，直接使用缓存中的顺序
				for (ExamQuestionsAnswer answer : examQuestionsOptionList) {
					String ordinaryQCode = answer.getOptionCode();
					String newQCode = (String) cachedMap.get(ordinaryQCode);
					answer.setOptionCode(newQCode);
				}
			}
		}

		// 对选项进行排序，确保显示顺序一致
		examQuestionsOptionList.sort(Comparator.comparing(ExamQuestionsAnswer::getOptionCode));

		ExamQuestionsProperty examQuestionsProperty = propertyMapper.selectExamQuestionsPropertyById(questionsCode);
		if ("3".equals(buildType)) {
			Map<String, Object> cacheMap = redisCache.getCacheMap(examCode + questionsCode + userId);


			if (ObjectUtil.isNotNull(cacheMap)){

				Integer questionsType = examQuestionsProperty.getQuestionsType();
				String rightAnswer = examQuestionsProperty.getRightAnswer();
				if (questionsType!=3){
					String o = (String) cacheMap.get(rightAnswer);
					contentData.setRightAnswer(o);
				}else {
					if (StringUtils.isNotBlank(rightAnswer)){
						String[] split = rightAnswer.split(",");
						ArrayList<String> list = new ArrayList<>();
						for (String s : split) {
							String o = (String) cacheMap.get(s);
							list.add(o);
						}
// 对选项进行排序
						list.sort(String::compareTo); // 默认按照字母顺序排序

// 拼接成 A,B,C,D 格式
						String result = String.join("", list);
						contentData.setRightAnswer(result);
					}

				}

			}



//			contentData.setRightAnswer((String)cacheMap.get(examQuestionsProperty.getRightAnswer()));
		}else {
			contentData.setRightAnswer(examQuestionsProperty.getRightAnswer());
		}




		String no = examQuestionsContentData.getNo();
		ExamFinishAnswer examFinishAnswer = new ExamFinishAnswer();
		examFinishAnswer.setNo(no);
		examFinishAnswer.setExamCode(examCode);
		examFinishAnswer.setQuestionsCode(questionsCode);
		examFinishAnswer.setUserCode(loginUser.getUser().getUserCode());
		ExamFinishAnswer fa = finishAnswerMapper.selectExamFinishAnswerByUserCodeQuestionsCodeNo(examFinishAnswer);
		if (StringUtils.isNotEmpty(no)) {
			// 查询 finishAnswer

			if (ObjectUtil.isNotNull(fa)) {
				String questionsAnswer = fa.getQuestionsAnswer();
				if(cachedMap == null || cachedMap.isEmpty()){
					contentData.setUserAnswer(questionsAnswer);
				}  else {
					int length = questionsAnswer.length();
					if (length>1){
						List<String> list = Arrays.stream(questionsAnswer.split(""))
								.collect(Collectors.toList());
						if (CollectionUtil.isNotEmpty(list)) {
							ArrayList<String> finalAnswers = new ArrayList<>();
							for (String s : list) {
								String o = (String) cachedMap.get(s);
								finalAnswers.add(o);
							}
							finalAnswers.sort(String::compareTo); // 默认按照字母顺序排序
							String result = String.join("", finalAnswers);
							contentData.setUserAnswer(result);
						}
					}else {
						String o = (String) cachedMap.get(questionsAnswer);
						contentData.setUserAnswer(o);
					}

				}

			}



		}
		ExamQuestionsData examQuestionsData = new ExamQuestionsData(contentData, examQuestionsOptionList);
		return examQuestionsData;
	}

}
